package ink.lovejinhu.leetcode;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author jinhu
 * created 2021-08-01 15:54
 */
public class Solution_0697 {
//    public static void main(String[] args) {
//        Solution_0697 solution_0697 = new Solution_0697();
//        int[] test = {1, 2, 2, 3, 1};
//        int shortestSubArray = solution_0697.findShortestSubArray(test);
//        System.out.println(shortestSubArray);
//    }

    public int findShortestSubArray(int[] nums) {
        HashMap<Integer, Res> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.containsKey(nums[i])) {
                Res res = hashMap.get(nums[i]);
                res.count++;
                res.end = i;
                hashMap.put(nums[i], res);
            } else {
                Res res = new Res();
                res.count = 1;
                res.start = i;
                res.end = i;
                hashMap.put(nums[i], res);
            }
        }
        ArrayList<Res> res = new ArrayList<>();
        System.out.println(hashMap);
        int max = 0;
        for (Integer integer : hashMap.keySet()
        ) {
            Res res1 = hashMap.get(integer);
            if (res1.count > max) {
                res.clear();
                res.add(res1);
                max= res1.count;
            } else if (res1.count == max) {
                res.add(res1);
                max= res1.count;
            }
        }
        System.out.println(res);
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < res.size(); i++) {
            Res res1 = res.get(i);
            if (res1.end - res1.start + 1 < min) {
                min = res1.end - res1.start + 1;
            }
        }
        return min;
    }

    class Res {
        int count;
        int start;
        int end;

        @Override
        public String toString() {
            return "Res{" +
                    "count=" + count +
                    ", start=" + start +
                    ", end=" + end +
                    '}';
        }
    }
}
